#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT "8080"
#define BUFFER_SIZE 1024

int main() {
    int sock;
    struct addrinfo hints, *res;
    char buffer[BUFFER_SIZE];
    char message[BUFFER_SIZE];

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;        
    hints.ai_socktype = SOCK_STREAM;  
    hints.ai_protocol = IPPROTO_TCP; 

    int status = getaddrinfo(SERVER_IP, SERVER_PORT, &hints, &res);
    if (status != 0) {
        exit(EXIT_FAILURE);
    }

    sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (sock == -1) {
        freeaddrinfo(res);
        exit(EXIT_FAILURE);
    }

    if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
        freeaddrinfo(res);
        exit(EXIT_FAILURE);
    }

    printf("Connected: %s\n", SERVER_IP);

    freeaddrinfo(res);

    while (1) {
        printf("Iceman> ");
        fgets(message, BUFFER_SIZE, stdin);
        message[strcspn(message, "\n")] = 0;

        if (strlen(message) == 0) continue;
        send(sock, message, strlen(message), 0);

        int bytes_received = recv(sock, buffer, BUFFER_SIZE - 1, 0);
        if (bytes_received <= 0) {
            break;
        }
        buffer[bytes_received] = '\0';
        printf("%s\n", buffer);
    }

    close(sock);
    return 0;
}
